package result

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var (
	SUCCESS = 0
	ERROR   = 1
)

type Result struct {
	Code    int    `json:"code"`    // 业务状态码
	Message string `json:"message"` // 提示信息
	Data    any    `json:"data"`    // 返回数据
}

func Ok(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Result{
		Code:    SUCCESS,
		Message: "SUCCESS",
		Data:    data,
	})
}

func Error(c *gin.Context, code int, message string) {
	c.JSON(http.StatusOK, Result{
		Code:    code,
		Message: message,
		Data:    nil,
	})
}

func Custom(c *gin.Context, code int, message string, data interface{}) {
	c.JSON(http.StatusOK, Result{
		Code:    code,
		Message: message,
		Data:    data,
	})
}

// ===== WebSocket 返回 =====
func WsOk(conn *websocket.Conn, data interface{}) error {
	return WsSend(conn, SUCCESS, "SUCCESS", data)
}

func WsError(conn *websocket.Conn, code int, message string) error {
	return WsSend(conn, code, message, nil)
}

func WsCustom(conn *websocket.Conn, code int, message string, data interface{}) error {
	return WsSend(conn, code, message, data)
}

func WsSend(conn *websocket.Conn, code int, message string, data interface{}) error {
	result := Result{
		Code:    code,
		Message: message,
		Data:    data,
	}
	bytes, err := json.Marshal(result)
	if err != nil {
		return err
	}
	return conn.WriteMessage(websocket.TextMessage, bytes)
}

func WsBinary(conn *websocket.Conn, data []byte) error {
	return conn.WriteMessage(websocket.BinaryMessage, data)
}

func Build(data any, code int, message string) string {
	result := Result{
		Code:    code,
		Message: message,
		Data:    data,
	}
	bytes, err := json.Marshal(result)
	if err != nil {
		// 出错时返回一个简单的 JSON，避免调用方再报错
		return `{"code":500,"message":"internal error","data":null}`
	}
	return string(bytes)
}
